package com.wenwei.sharebox.activity;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.bigkoo.pickerview.OptionsPickerView;
import com.bumptech.glide.Glide;
import com.lzy.imagepicker.ImagePicker;
import com.lzy.imagepicker.bean.ImageItem;
import com.lzy.imagepicker.ui.ImageGridActivity;
import com.lzy.imagepicker.view.CropImageView;
import com.tencent.cos.utils.FileUtils;
import com.wenwei.sharebox.R;
import com.wenwei.sharebox.base.BaseActivity;
import com.wenwei.sharebox.base.Constant;
import com.wenwei.sharebox.bean.UpdateUserInfoBean;
import com.wenwei.sharebox.bean.UserLoginBean;
import com.wenwei.sharebox.net.ApiManager;
import com.wenwei.sharebox.net.BaseSubscriber;
import com.wenwei.sharebox.upload.BizService;
import com.wenwei.sharebox.upload.PutObjectSample;
import com.wenwei.sharebox.utils.GlideImageLoader;
import com.wenwei.sharebox.utils.RogerSPUtils;
import com.wenwei.sharebox.utils.UserStringUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import de.hdodenhof.circleimageview.CircleImageView;

/**
 * Created by Administrator on 2017/7/13.
 */
public class UserInfoActivity extends BaseActivity {
    @Bind(R.id.base_title)
    TextView baseTitle;
    @Bind(R.id.base_save_tv)
    TextView baseSaveTv;
    @Bind(R.id.info_head)
    CircleImageView infoHead;
    @Bind(R.id.info_phone)
    TextView infoPhone;
    @Bind(R.id.info_nick)
    EditText infoNick;
    @Bind(R.id.info_sex)
    TextView infoSex;

    BizService bizService;
    private boolean isChangeUserInfo = false;//是否修改过用户资料
    @Override
    public int setLayoutResourceId() {
        return R.layout.activity_user_info;
    }

    @Override
    protected void init() {
        super.init();
        bizService = BizService.instance();
        bizService.init(getApplicationContext());
    }

    @Override
    protected void initView() {
        super.initView();
        baseTitle.setText("个人信息");
        UserLoginBean ub = RogerSPUtils.getObject(mContext, Constant.SP_USER_LOGIN_RESULT,UserLoginBean.class);
        userImg = ub.getProfile().getAvator();
        infoPhone.setText(ub.getUsername());
        infoNick.setText(ub.getProfile().getNickname());
        Glide.with(mContext).load(ub.getProfile().getAvator()).into(infoHead);
        if(ub.getProfile().getSex() == 1){
            infoSex.setText("男");
        }else {
            infoSex.setText("女");
        }

        ImagePicker imagePicker = ImagePicker.getInstance();
        imagePicker.setImageLoader(new GlideImageLoader());   //设置图片加载器
        imagePicker.setMultiMode(true);
        imagePicker.setShowCamera(true);  //显示拍照按钮
        imagePicker.setCrop(false);        //允许裁剪（单选才有效）
        imagePicker.setSaveRectangle(true); //是否按矩形区域保存
        imagePicker.setSelectLimit(1);    //选中数量限制
        imagePicker.setStyle(CropImageView.Style.RECTANGLE);  //裁剪框的形状
        imagePicker.setFocusWidth(800);   //裁剪框的宽度。单位像素（圆形自动取宽高最小值）
        imagePicker.setFocusHeight(800);  //裁剪框的高度。单位像素（圆形自动取宽高最小值）
        imagePicker.setOutPutX(1000);//保存文件的宽度。单位像素
        imagePicker.setOutPutY(1000);//保存文件的高度。单位像素

        infoNick.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                isChangeUserInfo = true;
                onUserInfoChanged();
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }

    private void onUserInfoChanged() {
        if (isChangeUserInfo) {
            baseSaveTv.setVisibility(View.VISIBLE);
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
        EventBus.getDefault().register(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    private static int IMAGE_PICKER = 99;
    @OnClick({R.id.base_back, R.id.base_save_tv, R.id.info_head,R.id.info_sex})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.base_back:
                finish();
                break;
            case R.id.base_save_tv:
                updateInfo();
                break;
            case R.id.info_head:
                goActivity(this, ImageGridActivity.class, null, IMAGE_PICKER);
                break;
            case R.id.info_sex:
                selectSex();
                break;
        }
    }

    OptionsPickerView pvOptions;
    private void selectSex() {
        pvOptions = new OptionsPickerView(this);
        final ArrayList<String> sexList = new ArrayList<>();
        sexList.add("男");
        sexList.add("女");
        pvOptions.setPicker(sexList);
        pvOptions.setTitle("选择性别");
        pvOptions.setSelectOptions(0);
        pvOptions.setCyclic(false);
        pvOptions.setOnoptionsSelectListener(new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int option2, int options3) {
                isChangeUserInfo = true;
                onUserInfoChanged();
                infoSex.setText(sexList.get(options1));
            }
        });
        pvOptions.show();
    }

    private String mCurrentFilePath;
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == ImagePicker.RESULT_CODE_ITEMS) {
            if (data != null && requestCode == IMAGE_PICKER) {
                ArrayList<ImageItem> images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
                for (ImageItem i : images) {
                    Log.d("msg", i.path);
                    Glide.with(mContext).load(Uri.fromFile(new File(i.path))).into(infoHead);
                    if(TextUtils.isEmpty(i.path)){
                        showToast("请选择图片");
                        return;
                    }
                    mCurrentFilePath = i.path;
                    new Thread(new Runnable() {
                        @Override
                        public void run() {

                            String filename = FileUtils.getFileName(mCurrentFilePath);
                            String cosPath =  "photo/" + new Date().getTime()+filename; //cos 上的路径
                            PutObjectSample.putObjectForSamllFile(bizService,cosPath,mCurrentFilePath);
                        }
                    }).start();
                }
            }
        }
    }


    private String userImg;
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(String event) {
        showToast("上传成功,请保存资料"+event);
        isChangeUserInfo = true;
        userImg = event;
        onUserInfoChanged();
    }

    private BaseSubscriber<UpdateUserInfoBean> infoSubscriber;
    private void updateInfo(){
        infoSubscriber = new BaseSubscriber<UpdateUserInfoBean>(mContext) {
            @Override
            public void onSuccess(UpdateUserInfoBean updateUserInfoBean) {
                showToast("修改成功");
                UserLoginBean ub = RogerSPUtils.getObject(mContext, Constant.SP_USER_LOGIN_RESULT,UserLoginBean.class);
                UserLoginBean.ProfileBean bean = ub.getProfile();
                bean.setAvator(userImg);
                bean.setSex(1);
                bean.setNickname(infoNick.getText().toString());
                ub.setProfile(bean);
                RogerSPUtils.putObject(mContext, Constant.SP_USER_LOGIN_RESULT,ub);
                setResult(RESULT_OK);
                finish();
            }
        };
        try{
            JSONObject jb = new JSONObject();
            jb.put("avator",userImg);
            jb.put("nickname",infoNick.getText().toString());
            if(infoSex.getText().toString().equals("男")){
                jb.put("sex",1);
            }else {
                jb.put("sex",0);
            }
            ApiManager.getInstance().updateUserInfo(infoSubscriber,jb.toString(), UserStringUtils.getUserId(mContext));
        }catch (Exception e){}
    }


}
